package cn.chengpengper.im.sdk.infrastructure.multicaster.impl;

import cn.chengpengper.im.common.domain.enums.ImListenerType;
import cn.chengpengper.im.common.domain.model.ImSendResult;
import cn.chengpengper.im.sdk.domain.annotation.ImListener;
import cn.chengpengper.im.sdk.domain.listener.MessageListener;
import cn.chengpengper.im.sdk.infrastructure.multicaster.MessageListenerMulticaster;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

@Component
public class DefaultMessageListenerMulticaster implements MessageListenerMulticaster {

    @Autowired(required = false)
    private List<MessageListener> messageListenerList = Collections.emptyList();

    @Override
    public <T> void multicast(ImListenerType listenerType, ImSendResult<T> result) {
        if (CollectionUtils.isEmpty(messageListenerList)) {
            return;
        }

        messageListenerList.forEach((messageListener -> {
            // 只有标注了@ImListener注解的实现类才会进行回调
            ImListener imListener = messageListener.getClass().getAnnotation(ImListener.class);
            if (Objects.nonNull(imListener) && (ImListenerType.ALL.equals(imListener.listenerType()) || imListener.listenerType().equals(listenerType))) {
                if (result.getData() instanceof JSONObject) {
                    Type superInterface = messageListener.getClass().getGenericInterfaces()[0];
                    Type type = ((ParameterizedType) superInterface).getActualTypeArguments()[0];
                    JSONObject data = (JSONObject) result.getData();
                    result.setData(data.toJavaObject(type));
                }
                messageListener.doProcess(result);
            }
        }));
    }
}
